package com.zl.easybuy.web;


import com.zl.easybuy.exception.EasyBuyException;
import com.zl.easybuy.pojo.Order;
import com.zl.easybuy.pojo.UserAddress;
import com.zl.easybuy.service.CartService;
import com.zl.easybuy.service.UserAddressService;
import com.zl.easybuy.vo.ResultCode;
import com.zl.easybuy.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/Cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private UserAddressService userAddressService;

    @PostMapping("/add")
    @ResponseBody
    public ResultVO add(Integer entityId,Integer quantity){
        try{
            boolean result = cartService.addCart(entityId,quantity);
            return result?ResultVO.success():ResultVO.returnFail(ResultCode.FAIl);
        }catch (EasyBuyException e){
            return ResultVO.returnFail(ResultCode.ADD_CART_FAIL);
        }
    }
    @RequestMapping("/refreshCart")
    public String refreshCart(){
        return "forward:/common/pre/searchBar.jsp";
    }


    //跳转到结算页面
    @RequestMapping("/toSettlement")
    public String toSettlement(){
        return "forward:/pre/settlement/toSettlement.jsp";
    }

    //结算1
    @RequestMapping("/settlement1")
    public String settlement1(){
        return "forward:/pre/settlement/settlement1.jsp";
    }
    /**
     * 修改数量
     */
    @PostMapping("/modifyCart")
    @ResponseBody
    public ResultVO modifyCart(Integer entityId,Integer quantity){
        try{
            boolean result =  cartService.modifyCart(entityId,quantity);
            return result?ResultVO.success():ResultVO.returnFail(ResultCode.FAIl);
        }catch(EasyBuyException e){  // 数量不足
            return ResultVO.returnFail(ResultCode.ADD_CART_FAIL);
        }
    }


    //跳转到结算2页面
    @RequestMapping("/settlement2")
    public String settlement2(Model model){
        //用户id 获取的session中的用户的id
        List<UserAddress> userAddressList = null;
        try {
            userAddressList = userAddressService.queryAddressByUserId();
            model.addAttribute("userAddressList",userAddressList);
            return "forward:/pre/settlement/settlement2.jsp";
        } catch (EasyBuyException e) {
            return "redirect:/User//page/login";
        }

    }
    //提交订单页面
    @RequestMapping("/settlement3")
    public String settlement3(Integer addressId,String newAddress,String newRemark,Model model) throws EasyBuyException{

        Order order = cartService.settlementCart(addressId,newAddress,newRemark);
        model.addAttribute("currentOrder",order);
        return "forward:/pre/settlement/settlement3.jsp";

    }
}
